package com.gitee.melin.bee.core.hibernate5.type;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import org.apache.commons.lang3.StringUtils;

@Converter
public class LongListConverter implements AttributeConverter<List<Long>, String> {

    @Override
    public String convertToDatabaseColumn(List<Long> list) {
        if (list == null) {
            return null;
        } else {
            return StringUtils.join(list, ",");
        }
    }

    @Override
    public List<Long> convertToEntityAttribute(String joined) {
        if (StringUtils.isNotBlank(joined)) {
            return Arrays.stream(joined.split(",")).map(Long::parseLong).collect(Collectors.toList());
        } else {
            return null;
        }
    }
}
